<?php
/**
 * 
 * Cosa class file
 * 
 * @author		Stijn Van Minnebruggen
 * @version		1.0.0
 * 
 */

class Cosa
{

	/**
	 * Holds the system charset type
	 * 
	 * @var		array
	 */
	
	private $_system;
	
	
	/**
	 * System language (short code)
	 * 
	 * @var		string
	 */
	
	public $language;
	
	
	/**
	 * Initialise class
	 * 
	 * @return	bool
	 */
	
	public function init()
	{
		
		// get db
			global $db;
			$this->_system = array();
			$this->language = DEFAULT_LANG;
		
		// check if system is installed
			$isInstalled = $this->_checkIfInstalled();
			$this->_system['installed'] = $isInstalled;
			if(!$isInstalled) {
				$this->_system['base-url'] = $this->_getURL();
				return false;
			}
		
		// get system vars
			$sql = "SELECT * FROM ".$db->table('settings')." WHERE type = 'system'";
			$res = mysql_query($sql) or $this->kill('Database error in main system library.', 'db');
			while($row = mysql_fetch_array($res)) $this->_system[$row['key']] = stripslashes($row['value']);
		
		// check for paths, add urls
			foreach($this->_system as $k => $v) {
				if(substr($k, strlen($k)-5) == '-path') {
					$this->_system[substr($k, 0, strlen($k)-5).'-url'] = $this->system('base-url').$v;
				}
			}
		
	}
	
	
	/**
	 * Check if all database database tables exist
	 * 
	 * @param	string	$var
	 * @return	bool
	 */
	
	private function _checkIfInstalled()
	{
		global $db;
		$cosaTables = array('domains', 'languages', 'languages_perm', 'modules', 'modules_perm', 'paths', 'plugins', 'settings', 'users', 'users_groups');
		foreach($cosaTables as $k => $table) { if(!$db->table_exists($db->table($table))) { return false; break; } }
		return true;
	}
	
	
	/**
	 * Get current URL
	 * 
	 * @return	string
	 */
	
	private function _getURL()
	{
		$fullurl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
		$filename = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/"));
		$url = str_replace($filename, '', $fullurl);
		return $url;
	}
	
	
	/**
	 * Get values from system
	 * 
	 * @param	string		$key
	 * @return	string
	 */
	
	public function system($key)
	{
		return (isset($this->_system[$key])) ? $this->_system[$key] : false;
	}
	
	
	/**
	 * Get values from settings
	 * 
	 * @param	string		$key
	 * @return	string
	 */
	
	public function settings($key)
	{
		$sql = "SELECT * FROM ".$db->table('settings')." WHERE type = 'system'";
		$res = mysql_query($sql) or $this->kill('Database error in main system library.', 'db');
		while($row = mysql_fetch_array($res)) $this->_system[$row['key']] = stripslashes($row['value']);
		return (isset($this->_settings[$key])) ? $this->_system[$key] : false;
	}
	
	
	/**
	 * Custom kill, standard php die in a better layout
	 * 
	 * @param	string		$message
	 * @param	string		$error			[optional]
	 * @return	void
	 */
	
	public function kill($message='', $error='fatal', $showHtml=true)
	{
		$error_type = array('fatal' => 'Fatal error!', 'stop' => 'Stopped.', 'db' => 'Database error!');
		if(!array_key_exists($error, $error_type)) $error = 'fatal';
		$html = '<html><head><title>Cosa</title><style type="text/css">body { background-color: #efefef; font-family: Arial,sans-serif; margin: 20px; font-size: 11px; } h1 { margin-bottom: 8px; font-size: 18px; } </style></head><body><h1>%s</h1>%s</body></html>';
		$die_message = ($showHtml) ? sprintf($html, $error_type[$error], $message) : $error_type[$error].' '.$message;
		die($die_message);
	}
	
	
	/**
	 * Custom kill, standard php die in a better layout
	 * 
	 * @param	string		$message
	 * @param	string		$error			[optional]
	 * @return	void
	 */
	
	public function oops($message='Oops.', $error='fatal')
	{
		$this->kill($message, $error, false);
	}
	
	
	
	/**
	 * Return formatted datetime (depending on system preference)
	 * 
	 * @param	string		$datetime
	 * @return	string
	 */
	
	public function datetime($datetime)
	{
		$format = $this->system('datetime');
		if(!$format || empty($format)) $format = 'Y-m-d H:i';
		$date = $this->parseDate($datetime);
		$time = mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year']);
		return date($format, $time);
	}
	
	
	/**
	 * Checks for date_parse availability
	 * 
	 * @param	string		$datetime
	 * @return	array
	 */
	
	private function parseDate($datetime)
	{
		if(!function_exists('date_parse')) {
			$l = strlen($datetime);
			if($l == 10) {			// 2009-01-01
				$h = $i = $s = 0;
			} else if($l == 16) {	// 2009-01-01 0:0:0
				$h = substr($datetime, 11, 1);
				$i = substr($datetime, 13, 1);
				$s = substr($datetime, 15, 1);
			} else {				// 2009-01-01 12:34:56
				$h = substr($datetime, 11, 2);
				$i = substr($datetime, 14, 2);
				$s = substr($datetime, 17, 2);
			}
			$m = substr($datetime, 5, 2); $d = substr($datetime, 8, 2); $y = substr($datetime, 0, 4);
			$time = mktime($h, $i, $s, $m, $d, $y);
			return array('year' => date('Y', $time), 'month' => date('n', $time), 'day' => date('j', $time), 'hour' => date('G', $time), 'minute' => date('i', $time), 'second' => date('s', $time));
		} else {
			return date_parse($datetime);
		}
	}
	
	
	/**
	 * Create html header
	 * 
	 * @return	void
	 */
	
	public function htmlHeader()
	{
		// required
			global $modules, $plugins;
		
		// fetch html headers
			$mdHtml = ($modules && method_exists($modules, 'htmlHeader')) ? $modules->htmlHeader() : false;
			$plHtml = ($plugins && method_exists($plugins, 'htmlHeader')) ? $plugins->htmlHeader() : false;
		
		// return result
			$html = '';
			if($mdHtml) $html .= $mdHtml;
			if($plHtml) $html .= $plHtml;
			echo $html;
		
	}
	
	
	/**
	 * Create html footer
	 * 
	 * @return	void
	 */
	
	public function htmlFooter()
	{
		// required
			global $modules, $plugins;
		
		// fetch html headers
			$mdHtml = ($modules && method_exists($modules, 'htmlFooter')) ? $modules->htmlFooter() : false;
			$plHtml = ($plugins && method_exists($plugins, 'htmlFooter')) ? $plugins->htmlFooter() : false;
		
		// return result
			$html = '';
			if($mdHtml) $html .= $mdHtml;
			if($plHtml) $html .= $plHtml;
			echo $html;
		
	}
	
}


?>